package rs.fon.is.music.parser;

import java.io.IOException;
import java.net.URI;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import rs.fon.is.music.domain.MusicRecording;
import rs.fon.is.music.parser.exceptions.MusicRecordingNotFoundException;
import rs.fon.is.music.persistence.DataModelManager;
import rs.fon.is.music.util.URIGenerator;

public class MusicRecordingParser implements DomainClassParser<MusicRecording> {

	@Override
	public MusicRecording parse(String url) {

		Document doc;
		
		try {
			doc = Jsoup.connect(url).get();

			Elements recordingElements = doc.getElementsByAttributeValue("itemtype","http://schema.org/MusicRecording");

			if (recordingElements.size() > 0) {

				MusicRecording recording = new MusicRecording();

				Element recordingElement = recordingElements.first();

				// URI
				recording.setUri(URIGenerator.generate(recording));

				// URL
				recording.setUrl(new URI(url));

				// name
				if (recordingElement.getElementsByAttributeValue("itemprop", "name").size() > 0)
					recording.setName(recordingElement.getElementsByAttributeValue("itemprop", "name").first().text());

				// interactionCount
				if (recordingElement.getElementsByAttributeValue("itemprop", "interactionCount").size() > 0)
					recording.setInteractionCount(recordingElement.getElementsByAttributeValue("itemprop","interactionCount").first().attr("content"));

				// keywords
				if (recordingElement.getElementsByAttributeValue("itemprop", "keywords").size() > 0){
					String keywordsString = recordingElement.getElementsByAttributeValue("itemprop", "keywords").first().attr("content");
					String [] keywords = keywordsString.split(",");
					for (String keyword : keywords) {
						recording.addKeyword(keyword.trim());
					}
				}	
				
				DataModelManager.getInstance().save(recording);
				
				return recording;

			} else
				throw new MusicRecordingNotFoundException("schema:MusicRecording instance is not found on this URL.");
		
		} catch (IOException e) {	
			return parse(url);
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}
}
